import base64
import hashlib
import json
import os
import random
from datetime import datetime

from flask import (
    Blueprint, request, session, current_app
)

from .db import get_db
from .taskQuene import pull_one_task

bp = Blueprint('CNA', __name__, url_prefix='/cna')


@bp.route('/get-task', methods=['GET',])
def get_task():
    if request.method == 'GET':
        node_ID = session.get('node_ID')
        # associated_UID = session.get('associated_UID')

        if node_ID is None:
            # get_db()
            node_ID = random.Random().randint(1, 1000000)
            print('赋予一个新ID')
            # g.db.cursor("")
            session.clear()
            session['node_ID'] = node_ID

        task, task_ID = pull_one_task(node_ID)
        if task_ID is not None:
            session['task_ID'] = task_ID

        return {
            'status': 'success',
            'task': task,
        }

    return {
        'status': 'unknown'
    }


@bp.route('/report-progress',methods=['POST'])
def report_progress():
    node_ID = session.get('node_ID')
    task_ID = session.get('task_ID')
    cur = get_db()
    percentage = request.json['percentage']
    cur.execute(f"UPDATE drawing_task_queue SET percentage={percentage} WHERE task_ID='{task_ID}'")
    return "copy that"


@bp.route('/result', methods=['POST'])
def hand_in_task():
    if request.method == 'POST':
        node_ID = session.get('node_ID')
        task_ID = session.get('task_ID')
        # print(request.json)
        cur = get_db()
        json_str = json.JSONEncoder().encode(request.json)

        file_byte = base64.b64decode(request.json['image']['raw_data'])
        file_md5 = hashlib.md5(file_byte).hexdigest()
        # print(file_md5)

        with open(os.path.join(current_app.root_path, 'static', 'drawing_result', (file_md5 + '.png')), 'wb') as f:
            f.write(file_byte)
            f.flush()

        cur.execute(f"SELECT UID FROM drawing_task_queue WHERE task_ID='{task_ID}'")
        UID = cur.fetchone()[0]
        cur.execute(
            f"UPDATE drawing_task_queue SET status='finish', result='{json_str}', finish_time='{datetime.now()}' WHERE task_ID='{task_ID}' "
        )

        del request.json['image']['raw_data']
        del request.json['image']['data_type']
        request.json['image']['url'] = '/static/drawing_result/' + file_md5
        print(request.json)
        cur.execute(
            f"INSERT INTO drawing VALUES ({UID},'{json.JSONEncoder().encode(request.json)}','{datetime.now()}','{task_ID}')"
        )
        return "succeed"
